package com.tiyende.kash.loop.ui.adapter

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lib.common.adapter.CommonOnItemChildClickListener
import com.lib.common.adapter.CommonRecyclerViewAdapter
import com.lib.common.adapter.CommonViewHolderHelper
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.TiyendeApp
import com.tiyende.kash.loop.event.TiyendeEventPointHelper
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.ui.dialog.TiyendeCustomerDialog
import com.tiyende.kash.loop.utils.helper.TiyendeConfigsHelper
import org.json.JSONObject
import java.math.BigDecimal

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/19 10:43
 * @Annotation：订单列表适配器
 */
class TiyendeOrderRepayListAdapter(recyclerView: RecyclerView?) : CommonRecyclerViewAdapter<JSONObject>(recyclerView) {

    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        val itemType = model.optString("itemType")
        return when(itemType){
            "emptyItemView" -> {//空
                R.layout.tiyende_activity_order_list_empty
            }
            "repayTipsItemView" -> {//强提醒
                R.layout.tiyende_fragment_order_repay_tips_item
            }
            else -> {
                R.layout.tiyende_fragment_order_repay_list_item
            }
        }
    }

    override fun setItemChildListener(helper: CommonViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.btOrderRepay)
    }

    override fun fillData(helper: CommonViewHolderHelper, position: Int, model: JSONObject) {
        val itemType = model.optString("itemType")
        when (itemType){
            "emptyItemView" -> {//空
//                val textWithdraw = helper.getTextView(R.id.textWithdraw)
//                textWithdraw.paint.flags = Paint.UNDERLINE_TEXT_FLAG//下划线
//                textWithdraw.paint.isAntiAlias = true//抗锯齿
            }
            "repayTipsItemView" -> {//强提醒
                showTiyendeOrderRepayTipsItemView(helper,position,model)
            }
            else -> {
                showTiyendeOrderRepayItemView(helper,position,model)
            }
        }
    }

    /**
     * 待还款订单强提醒
     */
    private fun showTiyendeOrderRepayTipsItemView(helper: CommonViewHolderHelper, position: Int, model: JSONObject){
        val customerListView = helper.getView<RecyclerView>(R.id.customerListView)
        customerListView.layoutManager = LinearLayoutManager(mContext)
        val customerAdapter = TiyendeCustomerDialog.CustomerItemAdapter(customerListView)
        customerListView.adapter = customerAdapter
        customerListView.itemAnimator = DefaultItemAnimator()
        customerAdapter.setOnItemChildClickListener(CommonOnItemChildClickListener { _, childView, position ->
            val item = customerAdapter.getItem(position)
            if (childView.id == R.id.btnCustomer) {
                if (item.optString("type") == "MOBILE"){
                    onCustomerMobileCallAction(item)
                }
            }
        })

        val contactList = arrayListOf<JSONObject>()
        val customize = TiyendeConfigsHelper.queryTiyendeConfigData()
        if (customize != null){
            val mobileStr = customize.optString("mobile","")
            if (mobileStr.isNotEmpty()){
                val mobileList = mobileStr.split(",")
                for (i in mobileList.indices){
                    val obj = JSONObject()
                    obj.put("type","MOBILE")
                    obj.put("value", mobileList[i])
                    contactList.add(obj)
                }
            }
            val emailStr = customize.optString("email","")
            if (emailStr.isNotEmpty()){
                val emailList = emailStr.split(",")
                for (i in emailList.indices){
                    val obj = JSONObject()
                    obj.put("type","EMAIL")
                    obj.put("value", emailList[i])
                    contactList.add(obj)
                }
            }
        }
        customerAdapter.data = contactList

        //工作时间
        //客服配置里没有配置工作时间，取主产品的工作时间展示
        var workDate = "Monday to Sunday"
        var workTime = "9:30am to 19:30pm."
        val customData = TiyendeConfigsHelper.queryTiyendeCustomData()
        customData?.let {
            if (!it.has("workDate") || !it.has("workTime")){
                val commonCustomData = TiyendeConfigsHelper.queryTiyendeCustomData()
                if (commonCustomData != null) {
                    it.put("workDate",commonCustomData.optString("workDate"))
                    it.put("workTime",commonCustomData.optString("workTime"))
                }
            }
            workDate = it.optString("workDate")
            workTime = it.optString("workTime")
        }
        helper.setText(R.id.customerTime,"$workDate,$workTime")
    }

    /**
     * 订单itemView
     */
    @SuppressLint("SetTextI18n")
    private fun showTiyendeOrderRepayItemView(helper: CommonViewHolderHelper, position: Int, model: JSONObject){
        //单位
        val unit = model.optString("currency")
        helper.setText(R.id.txtOrderRepayDueDate,String.format(getString(R.string.tiyende_order_repay_due_date),model.optString("repayTime")))
        helper.setText(R.id.txtOrderRepayIndex,String.format(getString(R.string.tiyende_order_repay_index),"$position"))
        helper.setText(R.id.txtOrderRepayTotal,String.format(getString(R.string.tiyende_order_repay_total_repayment),unit))
        helper.setText(R.id.txtOrderRepayTotalAmount,BigDecimal(model.optString("repayAmount","0.00")).stripTrailingZeros().setScale(2).toPlainString())
        helper.setText(R.id.txtOrderRepayInterest,BigDecimal(model.optString("interest","0.00")).stripTrailingZeros().setScale(2).toPlainString())
        helper.setText(R.id.txtOrderRepayOverdueDays,model.optString("overdueDay","0"))
        helper.setText(R.id.txtOrderRepayOverduePenalty,BigDecimal(model.optString("overdueFee","0.00")).stripTrailingZeros().setScale(2).toPlainString())

        val serviceFee = BigDecimal(model.optString("processingFee","0.00")).stripTrailingZeros().setScale(2).toFloat()
        if (serviceFee > 0){
            helper.setVisibility(R.id.txtOrderRepayServiceFeeTitle, View.VISIBLE)
            helper.setVisibility(R.id.txtOrderRepayServiceFee, View.VISIBLE)
            helper.setText(R.id.txtOrderRepayServiceFee,"$serviceFee")
        } else {
            helper.setVisibility(R.id.txtOrderRepayServiceFeeTitle, View.INVISIBLE)
            helper.setVisibility(R.id.txtOrderRepayServiceFee, View.INVISIBLE)
        }
    }

    private fun getString(strId: Int): String{
        return TiyendeApp.app.getString(strId)
    }


    /**
     * 拨号
     */
    private fun onCustomerMobileCallAction(item: JSONObject){
        val type = item.optString("type")
        TiyendeEventPointHelper.addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_KEFU_DIAL,type + "：" + item.optString("value"))
        val callIntent = Intent(Intent.ACTION_DIAL)
        callIntent.setData(Uri.parse("tel:${item.optString("value")}"))
        mContext.startActivity(callIntent)
    }
}